package org.amphiprion.montrictracv4.task.ludotheque;

import java.util.List;

import org.amphiprion.apiforanywebsite.engine.WebMarshaller;
import org.amphiprion.montrictracv4.ApplicationConstants;
import org.amphiprion.montrictracv4.db.model.Game;
import org.amphiprion.montrictracv4.db.model.GameExtension;
import org.amphiprion.montrictracv4.db.model.GameExtensionList;
import org.amphiprion.montrictracv4.db.model.GameLanguage;
import org.amphiprion.montrictracv4.web.model.WebExtensionOfGame;
import org.amphiprion.montrictracv4.web.model.WebExtensionsOfGame;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import android.content.Context;
import android.util.Log;

public class WebExtentionOfGameParser {
	private int gameParsed;
	private int nbGames;
	private Context context;
	private Game game;
	private SynchronizeExtensionOfGameTask task;

	WebExtentionOfGameParser(Context context, Game game, SynchronizeExtensionOfGameTask task) {

		this.context = context;
		this.game = game;
		this.task = task;
	}

	public GameExtensionList parse() {
		try {
			GameExtensionList result = new GameExtensionList();
			result.game = game;
			gameParsed = 0;
			int numPage = 1;
			while (numPage == 1 || gameParsed < nbGames) {
				boolean gamefound = collectPage(result, numPage);
				if (task.isCancelled()) {
					return null;
				}
				if (!gamefound) {
					break;
				}
				numPage++;
			}
			return result;
		} catch (Throwable e) {
			Log.e(ApplicationConstants.PACKAGE, "", e);
			return null;
		}
	}

	private boolean collectPage(GameExtensionList extList, int numPage) throws Throwable {

		String url = null;
		url = "http://www.trictrac.net/jeu-de-societe/les-jeux-du-jeu/" + game.getId() + "/extensions/scrollable/" + numPage + "/10";

		boolean succeed = false;
		int nbRetry = 0;
		int maxRetry = 3;
		Exception memE = null;
		Document doc = null;
		while (nbRetry <= maxRetry && !succeed) {
			try {
				doc = Jsoup.connect(url).get();
				succeed = true;
			} catch (Exception eee) {
				nbRetry++;
				memE = eee;
				Log.w(ApplicationConstants.PACKAGE, "Retry " + nbRetry + " due to " + eee.getClass().getName() + ": " + eee.getMessage());
			}
		}
		if (!succeed) {
			throw memE;
		}

		// Log.w(ApplicationConstants.PACKAGE, doc.html());
		WebMarshaller<WebExtensionsOfGame> m = new WebMarshaller<WebExtensionsOfGame>(WebExtensionsOfGame.class);
		List<WebExtensionsOfGame> list = m.marshall(doc);
		if (list.size() > 0) {
			WebExtensionsOfGame web = list.get(0);
			if (numPage == 1) {
				nbGames = new JSONObject(web.jsonDataConfig).getInt("total");
			}
			if (web.extensions == null || web.extensions.size() == 0) {
				return false;
			}
			for (WebExtensionOfGame game : web.extensions) {
				if (task.isCancelled()) {
					return false;
				}
				collectGame(extList, game);
			}
			return true;
		}
		return false;
	}

	private void collectGame(GameExtensionList extList, WebExtensionOfGame webGame) throws Exception {
		gameParsed++;
		task.publishProgress(gameParsed, nbGames);

		// Log.w(ApplicationConstants.PACKAGE, "ext: " + webGame.name);

		GameExtension ext = new GameExtension();

		String url = webGame.image;
		if (url.startsWith("/")) {
			url = ApplicationConstants.URL_ROOT + url;
		}
		ext.image = url;

		url = webGame.link;
		if (url.startsWith("/")) {
			url = ApplicationConstants.URL_ROOT + url;
		}
		int p2 = url.lastIndexOf('/');
		int p1 = url.lastIndexOf('/', p2 - 1);
		String id = url.substring(p1 + 1, p2);
		ext.id = id;

		ext.name = webGame.name;

		GameLanguage lang = new GameLanguage();

		url = webGame.langImage;
		if (url == null) {
			url = "/apps/translations/images/flags/fr.png";
			webGame.langName = "France";
		} else if (url.startsWith("/")) {
			url = ApplicationConstants.URL_ROOT + url;
		}
		lang.image = url;
		lang.name = webGame.langName;

		ext.lang = lang;

		if (!extList.languages.contains(lang)) {
			extList.languages.add(lang);
		}
		extList.extensions.add(ext);
	}
}
